/*
  EOMono
  Copyright 2007, Adam Tauno Williams (Whitemice Consulting)
  License: LGPLv2  < http://www.gnu.org/licenses/lgpl-2.1.html >
 */
using System;
using System.Data;
using System.Collections;
using System.Collections.Generic;

namespace Whitemice.EOMono
{
  public class EOSQLRecord : EORecord, IEORecord
  {
    protected bool                              isNew;
    
    public EOSQLRecord(IEOConnection conn, EOEntity e, bool committed)
      : base(conn, e)
    {
      isNew = (!(committed));
    } // end ctor;
       
    public bool IsNew 
    { 
      get 
      { 
        return isNew; 
      } 
    } // end IsNew
    
    public void Saved() 
    { 
      isNew = false; 
    }    
        
    public IList<string> PrimaryKeys
    { 
      get 
      { 
        return Entity.PrimaryKeys; 
      } 
    } // end PrimaryKeys
    
    public bool IsUpdateComplete
    {
      get
      {
        foreach(EOFieldDef f in Entity.Fields)
        {
          if ((f.IsPrimaryKey) && (this[f.Name].IsNull))
          {
            return false;
          }
        }
        return true;
      }
    } // end IsUpdateComplete
    
    public bool IsInsertComplete
    {
      get
      {
        if (EOModel.Entity(Entity.Name).MagicPrimaryKey)
          return true;
        return IsUpdateComplete;
      }
    } // end IsInsertComplete
    
    public string SQLValue(string fieldName)
    {
      EOFieldDef f = GetField(fieldName);
      return this[f.Name].SQLValue();
    } // end FormattedValue
    
    public void Save()
    {
      if (IsNew)
      {
        if (IsInsertComplete)
        {
          connection.Run(
            string.Format("{0}:{1}", Entity.Name, "SQLNew"),
            "record", this);
        } else throw new EONULLInPrimaryKeyException();
      } else
        {
          if (IsUpdateComplete)
          {
            connection.Run(
              string.Format("{0}:{1}", Entity.Name, "SQLSet"),
              "record", this);
          } else throw new EONULLInPrimaryKeyException();
        }
    } // end Save
    
    public void Delete()
    {
      connection.Run(
        string.Format("{0}:{1}", Entity.Name, "SQLDelete"),
        "record", this);    
    } // end Delete
  } // end class
}
